package com.leo.javase.thread.itcast;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号灯
 * @author Lian
 */
public class SemaphoreTest {

	public static void main(String[] args) {
		ExecutorService pool = Executors.newCachedThreadPool();
		
		final Semaphore sp = new Semaphore(3);
		
		for(int i=0; i<100; i++){
			Runnable task = new Runnable() {
				@Override
				public void run() {
					try {
						sp.acquire();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					System.out.println("线程"+Thread.currentThread().getName()+"进入，当前已有"+(3-sp.availablePermits())+"个并发");
					
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					System.out.println("线程"+Thread.currentThread().getName()+"即将离开");
					
					sp.release();
					
					System.out.println("线程"+Thread.currentThread().getName()+"已离开，当前已有"+(3-sp.availablePermits())+"个并发");
				}
			};
			
			pool.execute(task);
			
		}
		
		pool.shutdown();
	}

}
